<template>
  <div class="home-container">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 移动端分类导航 -->
      <div class="mobile-category-nav">
        <div class="category-scroll">
          <!-- 全部分类选项 -->
          <div
            class="category-item"
            :class="{ active: selectedCategoryId === undefined }"
            @click="clearCategorySelection"
          >
            <el-icon class="category-icon">
              <Grid />
            </el-icon>
            <span class="category-name">全部</span>
            <span class="category-count">({{ totalArticleCount }})</span>
          </div>

          <!-- 具体分类选项 -->
          <div
            v-for="category in categories"
            :key="category.id"
            class="category-item"
            :class="{ active: selectedCategoryId === category.id }"
            @click="selectCategory(category.id)"
          >
            <el-icon class="category-icon">
              <component :is="getCategoryIcon(category.icon)" />
            </el-icon>
            <span class="category-name">{{ category.name }}</span>
            <span class="category-count">({{ category.articleCount }})</span>
          </div>
        </div>
      </div>

      <!-- 桌面端左侧分类导航 -->
      <div class="left-sidebar desktop-only">
        <div class="sidebar-menu">
          <!-- 全部分类选项 -->
          <div
            class="menu-item"
            :class="{ active: selectedCategoryId === undefined }"
            @click="clearCategorySelection"
          >
            <el-icon>
              <Grid />
            </el-icon>
            <span>全部</span>
            <span class="article-count">({{ totalArticleCount }})</span>
          </div>

          <!-- 具体分类选项 -->
          <div
            v-for="category in categories"
            :key="category.id"
            class="menu-item"
            :class="{ active: selectedCategoryId === category.id }"
            @click="selectCategory(category.id)"
          >
            <el-icon>
              <component :is="getCategoryIcon(category.icon)" />
            </el-icon>
            <span>{{ category.name }}</span>
            <span class="article-count">({{ category.articleCount }})</span>
          </div>
        </div>
      </div>

      <!-- 中间内容区 -->
      <div class="center-content">
        <!-- 置顶公告组件 -->
        <TopAnnouncements ref="topAnnouncementsRef" />

        <!-- 搜索和排序区域 -->
        <div class="search-sort-section">
          <!-- 搜索框 -->
          <div class="search-wrapper">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索文章标题、内容..."
              size="large"
              class="search-input"
              clearable
              @keyup.enter="handleSearch"
              @clear="handleClearSearch"
            >
              <template #prefix>
                <el-icon class="search-icon">
                  <Search />
                </el-icon>
              </template>
            </el-input>
            <el-button
              type="primary"
              size="large"
              class="search-btn"
              @click="handleSearch"
            >
              <el-icon><Search /></el-icon>
              <span class="btn-text">搜索</span>
            </el-button>
          </div>

          <!-- 排序切换 -->
          <div class="sort-tabs">
            <div class="sort-label">排序：</div>
            <div class="sort-options">
              <div
                v-for="sortOption in sortOptions"
                :key="sortOption.value"
                class="sort-item"
                :class="{ active: currentSortType === sortOption.value }"
                @click="changeSortType(sortOption.value)"
              >
                <el-icon v-if="getSortIcon(sortOption.value)">
                  <component :is="getSortIcon(sortOption.value)" />
                </el-icon>
                <span>{{ sortOption.label }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 文章列表 -->
        <div v-loading="loading" class="article-list">
          <div
            v-for="article in articleList.records"
            :key="article.id"
            class="article-card"
            @click="viewArticle(article, $event)"
          >
            <!-- 移动端文章卡片布局 -->
            <div class="mobile-article-layout">
              <!-- 文章头部信息 -->
              <div class="article-header">
                <div class="author-section">
                  <div
                    class="author-info"
                    @click.stop="handleAuthorClick(article)"
                  >
                    <el-avatar
                      :size="28"
                      :src="formatAvatarUrl(article.authorAvatar)"
                      :alt="article.authorNickName || article.authorName"
                      fit="cover"
                      class="author-avatar"
                    >
                      <template #default>
                        <el-icon><User /></el-icon>
                      </template>
                    </el-avatar>
                    <div class="author-details">
                      <span class="author-name">{{
                        article.authorNickName || article.authorName
                      }}</span>
                      <span class="publish-time">{{
                        article.publishTime
                      }}</span>
                    </div>
                  </div>
                </div>
                <div class="article-meta">
                  <el-tag
                    v-if="isTruthy(article.isTop)"
                    size="small"
                    type="danger"
                    class="article-badge"
                    >置顶</el-tag
                  >
                  <el-tag
                    v-if="isTruthy(article.isOriginal)"
                    size="small"
                    type="success"
                    class="article-badge"
                    >原创</el-tag
                  >
                  <el-tag v-else size="small" type="info" class="article-badge"
                    >转载</el-tag
                  >
                </div>
              </div>

              <!-- 文章主体内容 -->
              <div class="article-main">
                <div class="article-content">
                  <h3 class="article-title">{{ article.title }}</h3>
                  <p class="article-summary">{{ article.summary }}</p>

                  <!-- 标签和操作按钮在同一行 -->
                  <div class="tags-actions-row">
                    <!-- 标签显示 -->
                    <div class="article-tags">
                      <template
                        v-if="article.articleTags && article.articleTags.length"
                      >
                        <el-tag
                          v-for="tag in article.articleTags.slice(0, 3)"
                          :key="`articleTag-${tag.id}`"
                          size="small"
                          class="tag-item"
                          :style="{
                            backgroundColor: tag.color,
                            color: '#ffffff',
                            border: `1px solid ${tag.color}`
                          }"
                        >
                          {{ tag.name }}
                        </el-tag>
                      </template>
                      <template
                        v-else-if="article.tags && article.tags.length > 0"
                      >
                        <el-tag
                          v-for="tag in article.tags.slice(0, 3)"
                          :key="`tag-${(tag as any).id || (tag as any).name}`"
                          size="small"
                          class="tag-item"
                          :style="{
                            backgroundColor: (tag as any).color || '#909399',
                            color: '#ffffff',
                            border: `1px solid ${(tag as any).color || '#909399'}`
                          }"
                        >
                          {{ (tag as any).name }}
                        </el-tag>
                      </template>
                    </div>

                    <!-- 右侧：统计信息和操作按钮 -->
                    <div class="right-actions">
                      <!-- 统计信息 -->
                      <span class="stat-item">
                        <el-icon><View /></el-icon>
                        <span class="stat-text">{{ article.viewCount }}</span>
                      </span>
                      <span class="stat-item">
                        <el-icon><ChatDotRound /></el-icon>
                        <span class="stat-text">{{
                          article.commentCount
                        }}</span>
                      </span>

                      <!-- 操作按钮 -->
                      <el-button
                        text
                        size="small"
                        class="action-btn like-btn"
                        :class="{ 'is-liked': isArticleLiked(article.id) }"
                        :loading="likeLoading[article.id]"
                        @click.stop="handleLike(article)"
                      >
                        <el-icon>
                          <LinearNewOhterLikeThumbUp
                            :class="{
                              'liked-icon': isArticleLiked(article.id)
                            }"
                          />
                        </el-icon>
                        <span class="action-text">{{ article.likeCount }}</span>
                      </el-button>

                      <el-button
                        text
                        size="small"
                        class="action-btn collect-btn"
                        :class="{
                          'is-collected': isArticleCollected(article.id)
                        }"
                        :loading="collectLoading[article.id]"
                        @click.stop="handleCollect(article)"
                      >
                        <el-icon>
                          <Star
                            :class="{
                              'collected-icon': isArticleCollected(article.id)
                            }"
                          />
                        </el-icon>
                        <span class="action-text">{{
                          article.collectCount
                        }}</span>
                      </el-button>
                    </div>
                  </div>
                </div>

                <!-- 文章封面图 -->
                <div v-if="article.coverImage" class="article-cover">
                  <img
                    :src="formatImageUrl(article.coverImage)"
                    :alt="article.title"
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- 移动端分页 -->
          <div v-if="articleList.total > 0" class="pagination-wrapper">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="articleList.total"
              :page-sizes="[10, 20, 50]"
              :layout="paginationLayout"
              :small="isMobile"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>

      <!-- 右侧边栏 -->
      <div class="right-sidebar desktop-only">
        <div class="sidebar-sticky">
          <!-- 问候卡片 -->
          <div v-if="userAuthStore.isLoggedIn" class="greeting-card">
            <div class="greeting-content">
              <h3>{{ greeting }}</h3>
              <p>{{ greetingSubtitle }}</p>
            </div>
          </div>

          <!-- 文章榜 -->
          <div class="ranking-card">
            <div class="ranking-header">
              <h4>文章榜</h4>
              <div class="ranking-actions">
                <span class="refresh-btn" @click="refreshHotRanking"
                  >换一换</span
                >
                <span class="more-btn" @click="viewMoreHotArticles"
                  >查看更多</span
                >
              </div>
            </div>
            <div class="rank-list">
              <div
                v-for="article in displayedHotArticles"
                :key="article.targetId"
                v-tippy="{ content: article.title, placement: 'left' }"
                class="rank-item"
                @click="router.push(`/user/article/${article.targetId}`)"
              >
                <div class="rank-number">{{ article.rank }}</div>
                <div class="article-info">
                  <div class="article-title">{{ article.title }}</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 作者榜 -->
          <div class="ranking-card author-ranking">
            <div class="ranking-header">
              <h4>作者榜</h4>
              <div class="ranking-actions">
                <span class="refresh-btn" @click="refreshAuthorRanking"
                  >换一换</span
                >
                <span class="more-btn" @click="viewMoreAuthors">查看更多</span>
              </div>
            </div>
            <div class="author-list">
              <div
                v-for="author in displayedAuthors"
                :key="author.targetId"
                class="author-item"
              >
                <el-avatar
                  :size="36"
                  :src="formatAvatarUrl(author.avatar)"
                  :alt="author.title"
                  fit="cover"
                  class="author-avatar"
                  @click="router.push(`/user/profile/${author.authorId}`)"
                >
                  <template #default>
                    <el-icon><User /></el-icon>
                  </template>
                </el-avatar>
                <div
                  class="author-info"
                  @click="router.push(`/user/profile/${author.authorId}`)"
                >
                  <div class="author-name">{{ author.title }}</div>
                  <div v-if="author.subtitle" class="author-signature">
                    {{ author.subtitle }}
                  </div>
                </div>
                <span
                  class="follow-text"
                  :class="{ 'is-followed': author.isFollowed }"
                  @click.stop="handleFollowAuthorInRanking(author)"
                >
                  {{ author.isFollowed ? "已关注" : "+ 关注" }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 公告弹窗组件 -->
  <AnnouncementPopup ref="announcementPopupRef" />
</template>

<script setup lang="ts">
import { LinearNewOhterLikeThumbUp } from "@element-extended-icon-pack/vue";
import {
  ref,
  computed,
  onMounted,
  watch,
  onActivated,
  onBeforeUnmount
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  Star,
  Postcard,
  Monitor,
  Iphone,
  Cpu,
  Tools,
  Reading,
  View,
  ChatDotRound,
  Grid,
  User,
  Search,
  Clock,
  TrendCharts,
  Promotion,
  ChatLineRound
} from "@element-plus/icons-vue";
import { useUserAuthStore } from "@/store/modules/userAuth";
import { formatAvatarUrl, formatImageUrl, isTruthy } from "@/utils/avatar";

import {
  getCategories,
  getArticles,
  getRecommendedAuthors,
  type Category,
  type Article,
  type ArticleList,
  type RecommendedAuthor,
  type HomeQueryParams
} from "@/api/home";
import {
  getArticleOverallRanking,
  getAuthorOverallRanking,
  type RankingItem
} from "@/api/ranking";
import { likeUserArticleApi, collectUserArticleApi } from "@/api/user-article";
import { followUserApi } from "@/api/user-profile";
import TopAnnouncements from "@/views/user/announcement/components/TopAnnouncements.vue";
import AnnouncementPopup from "@/views/user/announcement/components/AnnouncementPopup.vue";
import { SeoUtil } from "@/utils/seo";

defineOptions({
  name: "UserHome"
});

const router = useRouter();
const userAuthStore = useUserAuthStore();

// 公告组件引用
const topAnnouncementsRef = ref();
const announcementPopupRef = ref();

// 数据状态
const loading = ref(false);
const categories = ref<Category[]>([]);
const articleList = ref<ArticleList>({
  records: [],
  total: 0,
  current: 1,
  size: 10,
  pages: 0,
  hasNext: false
});
const rankings = ref({
  hotArticles: [] as RankingItem[],
  likedArticles: [] as RankingItem[],
  recommendedAuthors: [] as RecommendedAuthor[]
});

// 关注状态管理
const followingStates = ref<Record<number, boolean>>({});
const authorFollowingStates = ref<Record<number, boolean>>({});

// 榜单显示控制
const maxDisplayCount = 5; // 最多显示5个条目

// 计算属性：显示的热门文章（只显示前5个）
const displayedHotArticles = computed(() => {
  if (
    !rankings.value.hotArticles ||
    !Array.isArray(rankings.value.hotArticles)
  ) {
    return [];
  }
  return rankings.value.hotArticles.slice(0, maxDisplayCount);
});

// 计算属性：显示的点赞文章（只显示前5个）
const displayedLikedArticles = computed(() => {
  if (
    !rankings.value.likedArticles ||
    !Array.isArray(rankings.value.likedArticles)
  ) {
    return [];
  }
  return rankings.value.likedArticles.slice(0, maxDisplayCount);
});

// 计算属性：显示的作者（只显示前5个）
const displayedAuthors = computed(() => {
  if (
    !rankings.value.recommendedAuthors ||
    !Array.isArray(rankings.value.recommendedAuthors)
  ) {
    return [];
  }
  return rankings.value.recommendedAuthors.slice(0, maxDisplayCount);
});

// 计算属性：总文章数量（所有分类的文章数量之和）
const totalArticleCount = computed(() => {
  return categories.value.reduce(
    (total, category) => total + category.articleCount,
    0
  );
});

// 查询参数
const searchKeyword = ref("");

// 点赞和收藏的loading状态
const likeLoading = ref<Record<number, boolean>>({});
const collectLoading = ref<Record<number, boolean>>({});

// 移除本地缓存，直接使用全局状态确保一致性

// 页面可见性变化时重新加载文章列表
const handleVisibilityChange = async () => {
  if (!document.hidden) {
    console.log("🔄 页面变为可见，重新加载文章列表");
    try {
      await loadArticles();
      console.log("✅ 页面可见性文章列表刷新完成");
    } catch (error) {
      console.error("❌ 页面可见性文章列表刷新失败:", error);
    }
  }
};

// 移除滚动监听逻辑，改用CSS自适应高度方案

// 从本地存储恢复分类选择状态
const getStoredCategoryId = (): number | undefined => {
  const stored = localStorage.getItem("home-selected-category");
  if (stored && stored !== "undefined") {
    const id = parseInt(stored);
    return isNaN(id) ? undefined : id;
  }
  return undefined;
};

const selectedCategoryId = ref<number | undefined>(getStoredCategoryId());
const currentSortType = ref<"latest" | "hot" | "liked" | "commented">("latest");
const currentPage = ref(1);
const pageSize = ref(10);

// 响应式检测
const isMobile = ref(false);

// 分页布局配置
const paginationLayout = computed(() => {
  return isMobile.value
    ? "prev, pager, next"
    : "total, sizes, prev, pager, next, jumper";
});

// 排序选项
const sortOptions = [
  { label: "最新", value: "latest" as const },
  { label: "热门", value: "hot" as const },
  { label: "点赞", value: "liked" as const },
  { label: "评论", value: "commented" as const }
];

// 检测移动端
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768;
};

// 问候语
const greeting = computed(() => {
  const hour = new Date().getHours();
  if (hour < 12) return "上午好";
  if (hour < 18) return "下午好";
  return "晚上好";
});

const greetingSubtitle = computed(() => {
  return `欢迎回来，${userAuthStore.nickName || userAuthStore.userName}！`;
});

// 获取分类图标组件
const getCategoryIcon = (iconName: string) => {
  const iconMap: Record<string, any> = {
    "tech-icon": Monitor,
    "life-icon": Reading,
    "backend-icon": Postcard,
    "frontend-icon": Monitor,
    "mobile-icon": Iphone,
    "ai-icon": Cpu,
    "tools-icon": Tools,
    default: Star
  };
  return iconMap[iconName] || iconMap.default;
};

// 获取排序图标
const getSortIcon = (sortType: string) => {
  const iconMap: Record<string, any> = {
    latest: Clock,
    hot: TrendCharts,
    liked: Promotion,
    commented: ChatLineRound
  };
  return iconMap[sortType];
};

// formatAvatarUrl 函数现在从工具模块导入

// 加载分类数据
const loadCategories = async () => {
  try {
    console.log("开始加载分类数据...");
    const response = await getCategories();
    console.log("分类数据响应:", response);
    // API返回格式: { code: 200, message: "...", data: [...] }
    const data = (response as any)?.data || response;
    categories.value = Array.isArray(data) ? data : [];
    console.log("分类数据设置完成:", categories.value);
  } catch (error) {
    console.error("加载分类数据失败:", error);
    ElMessage.error("加载分类失败，请稍后重试");
  }
};

// 加载榜单数据
const loadRankings = async () => {
  try {
    console.log("开始加载榜单数据...");
    const [articleRanking, authorRanking] = await Promise.all([
      getArticleOverallRanking(1, 5), // 文章综合榜
      getAuthorOverallRanking(1, 5) // 作者综合榜
    ]);

    console.log("榜单数据响应:", {
      articleRanking,
      authorRanking
    });

    // 提取榜单数据
    const hotData = articleRanking?.data?.records || [];
    const authorsData = authorRanking?.data?.records || [];

    rankings.value = {
      hotArticles: Array.isArray(hotData) ? hotData : [],
      likedArticles: [],
      recommendedAuthors: Array.isArray(authorsData) ? authorsData : []
    };
    console.log("榜单数据设置完成:", rankings.value);
  } catch (error) {
    console.error("加载榜单数据失败:", error);
    ElMessage.error("加载榜单失败，请稍后重试");
  }
};

// 加载首页数据
const loadHomeData = async () => {
  try {
    loading.value = true;

    // 并行加载分类和榜单数据
    await Promise.all([loadCategories(), loadRankings()]);

    // 加载文章列表
    await loadArticles();
  } catch (error) {
    console.error("加载首页数据失败:", error);
    ElMessage.error("加载数据失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 加载文章列表
const loadArticles = async () => {
  try {
    const params: HomeQueryParams = {
      current: currentPage.value,
      size: pageSize.value,
      categoryId: selectedCategoryId.value,
      keyword: searchKeyword.value,
      sortType: currentSortType.value
    };

    console.log("开始加载文章列表，参数:", params);
    const response = await getArticles(params);
    console.log("文章列表响应:", response);

    // API返回格式: { code: 200, message: "...", data: {...} }
    const data = (response as any)?.data || response;

    // 确保数据格式正确
    if (data && typeof data === "object") {
      articleList.value = {
        records: Array.isArray(data.records) ? data.records : [],
        total: data.total || 0,
        current: data.current || 1,
        size: data.size || 10,
        pages: data.pages || 0,
        hasNext: data.hasNext || false
      };
    } else {
      articleList.value = {
        records: [],
        total: 0,
        current: 1,
        size: 10,
        pages: 0,
        hasNext: false
      };
    }
    console.log("文章列表设置完成:", articleList.value);

    // 调试标签信息
    if (articleList.value.records.length > 0) {
      const firstArticle = articleList.value.records[0];
      console.log("第一篇文章的标签信息:", {
        id: firstArticle.id,
        title: firstArticle.title,
        tags: firstArticle.tags,
        articleTags: firstArticle.articleTags,
        tagCount: firstArticle.tagCount
      });
    }
  } catch (error) {
    console.error("加载文章列表失败:", error);
    ElMessage.error("加载文章失败，请稍后重试");
  }
};

// 选择分类
const selectCategory = (categoryId: number) => {
  selectedCategoryId.value = categoryId;
  // 保存到本地存储
  localStorage.setItem("home-selected-category", categoryId.toString());
  currentPage.value = 1; // 重置页码
  loadArticles();
  // 滚动到页面顶部
  window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
};

// 清除分类选择
const clearCategorySelection = () => {
  selectedCategoryId.value = undefined;
  // 清除本地存储
  localStorage.removeItem("home-selected-category");
  currentPage.value = 1; // 重置页码
  loadArticles();
  // 滚动到页面顶部
  window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
};

// 切换排序类型
const changeSortType = (sortType: "latest" | "hot" | "liked" | "commented") => {
  currentSortType.value = sortType;
  currentPage.value = 1; // 重置页码
  loadArticles();
};

// 搜索功能
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    console.log("🔍 开始搜索:", searchKeyword.value.trim());
    currentPage.value = 1; // 重置页码
    loadArticles();
    ElMessage.info(`正在搜索: ${searchKeyword.value.trim()}`);
  } else {
    ElMessage.warning("请输入搜索关键词");
  }
};

// 清除搜索
const handleClearSearch = () => {
  searchKeyword.value = "";
  currentPage.value = 1; // 重置页码
  loadArticles();
  console.log("🗑️ 已清除搜索关键词");
};

// 导航点击处理已移至全局布局
// const handleNavClick = (nav: string) => {
//   console.log("导航点击:", nav);
//   // TopNavigation 组件会处理默认的导航逻辑
// };

// 查看文章详情
const viewArticle = (article: Article | any, event?: Event) => {
  // 阻止默认行为和事件冒泡
  if (event) {
    event.preventDefault();
    event.stopPropagation();
  }

  console.log("🔗 点击文章，准备在新标签页打开:", article.id);

  // 以新标签页打开文章详情，符合主流论坛交互习惯
  const route = router.resolve(`/user/article/${article.id}`);
  // 使用完整URL，确保 Hash 模式路由正确解析
  const fullUrl =
    window.location.origin + window.location.pathname + route.href;
  console.log("🔗 完整URL:", fullUrl);

  const newWindow = window.open(fullUrl, "_blank");

  if (!newWindow) {
    console.warn("⚠️ 浏览器阻止了弹出窗口，尝试使用 router.push");
    router.push(`/user/article/${article.id}`);
  } else {
    console.log("✅ 成功在新标签页打开文章");
  }
};

// 处理作者点击
const handleAuthorClick = (article: Article | any) => {
  const authorId = article.authorId;
  if (authorId) {
    console.log(`👤 点击作者，跳转到用户主页: ${authorId}`);
    router.push(`/user/profile/${authorId}`);
  } else {
    console.warn("❌ 作者ID不存在，无法跳转");
  }
};

// 根据ID跳转到作者主页
const handleAuthorClickById = (authorId: number) => {
  console.log(`👤 点击作者ID: ${authorId}`);
  if (!authorId) {
    console.warn("缺少authorId");
    return;
  }
  router.push(`/user/profile/${authorId}`);
};

// 处理关注/取消关注作者
const handleFollowAuthor = async (author: RecommendedAuthor) => {
  // 检查是否登录
  if (!userAuthStore.isLoggedIn) {
    ElMessage.warning("请先登录后再关注作者");
    router.push("/user/login");
    return;
  }

  // 防止重复点击
  if (followingStates.value[author.userId]) {
    return;
  }

  try {
    followingStates.value[author.userId] = true;
    const isFollowing = !author.isFollowed;

    const response = await followUserApi({
      userId: author.userId,
      isFollow: isFollowing
    });

    if (response.code === 200) {
      // 更新关注状态
      author.isFollowed = isFollowing;

      // 更新粉丝数
      if (isFollowing) {
        author.followerCount++;
        ElMessage.success(`已关注 ${author.nickName || author.userName}`);
      } else {
        author.followerCount--;
        ElMessage.info(`已取消关注 ${author.nickName || author.userName}`);
      }
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("关注操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  } finally {
    followingStates.value[author.userId] = false;
  }
};

// 检查文章是否已点赞（使用后端返回的isLiked字段）
const isArticleLiked = (articleId: number): boolean => {
  const article = articleList.value.records.find(item => item.id === articleId);
  const isLiked = (article as any)?.isLiked || false;
  console.log(
    `🔍 点赞状态检查 - 文章ID: ${articleId}, isLiked字段: ${isLiked}`
  );
  return isLiked;
};

// 检查文章是否已收藏（使用后端返回的isCollected字段）
const isArticleCollected = (articleId: number): boolean => {
  const article = articleList.value.records.find(item => item.id === articleId);
  const isCollected = (article as any)?.isCollected || false;
  console.log(
    `🔍 收藏状态检查 - 文章ID: ${articleId}, isCollected字段: ${isCollected}`
  );
  return isCollected;
};

// 处理文章点赞
const handleLike = async (article: Article | any) => {
  // 检查用户是否已登录
  if (!userAuthStore.isLoggedIn) {
    ElMessage.warning("请先登录后再进行点赞操作");
    router.push("/user/login");
    return;
  }

  const articleId = article.id;
  const isCurrentlyLiked = isArticleLiked(articleId);
  const newLikeState = !isCurrentlyLiked; // 切换状态

  // 设置loading状态
  likeLoading.value[articleId] = true;

  try {
    console.log(
      `🚀 开始点赞操作 - 文章ID: ${articleId}, 当前状态: ${isCurrentlyLiked}, 新状态: ${newLikeState}`
    );
    console.log(
      `📋 调用API: likeUserArticleApi(${articleId}, ${newLikeState})`
    );

    const response = await likeUserArticleApi(articleId, newLikeState);
    console.log(`📥 API响应:`, response);

    if (response.code === 200) {
      // 直接更新文章的状态字段和统计数据
      const currentArticle = articleList.value.records.find(
        item => item.id === articleId
      );
      if (currentArticle) {
        (currentArticle as any).isLiked = newLikeState;
        currentArticle.likeCount += newLikeState ? 1 : -1;
        console.log(`✅ 已更新文章 ${articleId} 的点赞状态为: ${newLikeState}`);
      }

      ElMessage.success(newLikeState ? "点赞成功" : "取消点赞成功");
    } else {
      console.error("点赞API响应错误:", response);
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("点赞操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  } finally {
    likeLoading.value[articleId] = false;
  }
};

// 处理文章收藏
const handleCollect = async (article: Article | any) => {
  // 检查用户是否已登录
  if (!userAuthStore.isLoggedIn) {
    ElMessage.warning("请先登录后再进行收藏操作");
    router.push("/user/login");
    return;
  }

  const articleId = article.id;
  const isCurrentlyCollected = isArticleCollected(articleId);
  const newCollectState = !isCurrentlyCollected; // 切换状态

  // 设置loading状态
  collectLoading.value[articleId] = true;

  try {
    console.log(
      `🚀 开始收藏操作 - 文章ID: ${articleId}, 当前状态: ${isCurrentlyCollected}, 新状态: ${newCollectState}`
    );
    console.log(
      `📋 调用API: collectUserArticleApi(${articleId}, ${newCollectState})`
    );

    const response = await collectUserArticleApi(articleId, newCollectState);
    console.log(`📥 API响应:`, response);

    if (response.code === 200) {
      // 直接更新文章的状态字段和统计数据
      const currentArticle = articleList.value.records.find(
        item => item.id === articleId
      );
      if (currentArticle) {
        (currentArticle as any).isCollected = newCollectState;
        currentArticle.collectCount += newCollectState ? 1 : -1;
        console.log(
          `✅ 已更新文章 ${articleId} 的收藏状态为: ${newCollectState}`
        );
      }

      ElMessage.success(newCollectState ? "收藏成功" : "取消收藏成功");
    } else {
      console.error("收藏API响应错误:", response);
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  } finally {
    collectLoading.value[articleId] = false;
  }
};

// 榜单当前页码
const hotRankingPage = ref(1);
const authorRankingPage = ref(1);

// 换一换文章榜
const refreshHotRanking = async () => {
  try {
    hotRankingPage.value += 1;

    const response = await getArticleOverallRanking(hotRankingPage.value, 5);
    const data = response?.data?.records || [];

    if (Array.isArray(data) && data.length > 0) {
      rankings.value.hotArticles = data;
      ElMessage.success("文章榜已刷新");
    } else {
      // 如果没有更多数据，重置到第一页
      hotRankingPage.value = 1;
      const firstPageResponse = await getArticleOverallRanking(1, 5);
      const firstPageData = firstPageResponse?.data?.records || [];
      rankings.value.hotArticles = Array.isArray(firstPageData)
        ? firstPageData
        : [];
      ElMessage.success("已回到第一页");
    }
  } catch (error) {
    console.error("刷新文章榜失败:", error);
    ElMessage.error("刷新失败，请稍后重试");
  }
};

// 换一换作者榜
const refreshAuthorRanking = async () => {
  try {
    authorRankingPage.value += 1;

    const response = await getAuthorOverallRanking(authorRankingPage.value, 5);
    const data = response?.data?.records || [];

    if (Array.isArray(data) && data.length > 0) {
      rankings.value.recommendedAuthors = data;
      ElMessage.success("作者榜已刷新");
    } else {
      // 如果没有更多数据，重置到第一页
      authorRankingPage.value = 1;
      const firstPageResponse = await getAuthorOverallRanking(1, 5);
      const firstPageData = firstPageResponse?.data?.records || [];
      rankings.value.recommendedAuthors = Array.isArray(firstPageData)
        ? firstPageData
        : [];
      ElMessage.success("已回到第一页");
    }
  } catch (error) {
    console.error("刷新作者榜失败:", error);
    ElMessage.error("刷新失败，请稍后重试");
  }
};

// 查看更多文章榜
const viewMoreHotArticles = () => {
  router.push({
    path: "/user/ranking",
    query: { type: "article", dimension: "overall" }
  });
};

// 查看更多作者榜
const viewMoreAuthors = () => {
  router.push({
    path: "/user/ranking",
    query: { type: "author", dimension: "overall" }
  });
};

// 处理作者榜关注/取消关注
const handleFollowAuthorInRanking = async (author: RankingItem) => {
  // 检查是否登录
  if (!userAuthStore.isLoggedIn) {
    ElMessage.warning("请先登录后再关注作者");
    router.push("/user/login");
    return;
  }

  const authorId = author.authorId;
  if (!authorId) return;

  // 防止重复点击
  if (authorFollowingStates.value[authorId]) {
    return;
  }

  try {
    authorFollowingStates.value[authorId] = true;
    const isFollowing = !author.isFollowed;

    const response = await followUserApi({
      userId: authorId,
      isFollow: isFollowing
    });

    if (response.code === 200) {
      // 更新关注状态
      author.isFollowed = isFollowing;

      // 更新粉丝数
      if (author.fansCount !== undefined) {
        author.fansCount += isFollowing ? 1 : -1;
      }

      ElMessage.success(
        isFollowing ? `已关注 ${author.title}` : `已取消关注 ${author.title}`
      );
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("关注操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  } finally {
    authorFollowingStates.value[authorId] = false;
  }
};

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadArticles();
  // 滚动到页面顶部
  window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  loadArticles();
  // 滚动到页面顶部
  window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
};

// 监听搜索关键词变化
watch(searchKeyword, newKeyword => {
  if (newKeyword.trim() === "") {
    // 如果搜索关键词为空，重新加载数据
    currentPage.value = 1;
    loadArticles();
  }
});

onMounted(async () => {
  console.log("组件挂载，开始加载数据...");

  // 初始化移动端检测
  checkMobile();
  window.addEventListener("resize", checkMobile);

  // 确保页面滚动到顶部
  window.scrollTo({ top: 0, left: 0, behavior: "auto" });

  // 组件挂载后加载首页数据
  try {
    await loadHomeData();
    console.log("首页数据加载完成");
  } catch (error) {
    console.error("首页数据加载失败:", error);
  }

  // 设置首页SEO（等待SEO配置初始化完成）
  try {
    // 如果SEO配置还没初始化，等待初始化完成
    if (!(SeoUtil as any).seoConfig) {
      await SeoUtil.init();
    }
    const structuredData = await SeoUtil.getWebsiteStructuredData();
    if (structuredData) {
      // 使用document API直接添加结构化数据
      let scriptTag = document.querySelector(
        'script[type="application/ld+json"]'
      );
      if (!scriptTag) {
        scriptTag = document.createElement("script");
        scriptTag.type = "application/ld+json";
        document.head.appendChild(scriptTag);
      }
      scriptTag.textContent = structuredData;
    }
  } catch (error) {
    console.error("首页SEO设置失败:", error);
  }

  // 如果store中没有用户信息但存储中有，尝试手动恢复
  if (!userAuthStore.isLoggedIn) {
    const localData = localStorage.getItem("user-auth-info");
    const sessionData = sessionStorage.getItem("user-auth-info");

    if (localData || sessionData) {
      try {
        const userData = localData
          ? JSON.parse(localData)
          : JSON.parse(sessionData);
        if (userData && userData.token) {
          // 检查token是否过期
          const currentTimestamp = Math.floor(Date.now() / 1000);
          const expireTime =
            userData.expireTime < currentTimestamp
              ? currentTimestamp + userData.expireTime
              : userData.expireTime;

          if (expireTime > currentTimestamp) {
            userAuthStore.setUserInfo(userData, userData.isRemembered || false);
          }
        }
      } catch (error) {
        console.error("恢复用户状态失败:", error);
      }
    }
  }

  // 用户交互数据（点赞、收藏状态）已由 loadArticles() 从后端获取
  // 文章列表中的 isLiked 和 isCollected 字段直接反映用户的交互状态
  if (userAuthStore.isLoggedIn) {
    console.log("✅ 用户已登录，文章交互状态将通过API自动获取");
  }

  // 添加页面可见性监听器
  document.addEventListener("visibilitychange", handleVisibilityChange);
});

// 页面激活时（从其他页面返回）重新加载文章列表
onActivated(async () => {
  console.log("🔄 页面激活，重新加载文章列表以获取最新状态");

  try {
    // 重新加载文章列表，获取最新的isLiked和isCollected状态
    await loadArticles();
    console.log("✅ 页面激活后文章列表已刷新");
  } catch (error) {
    console.error("❌ 页面激活后文章列表刷新失败:", error);
  }
});

// 组件卸载时清理监听器
onBeforeUnmount(() => {
  document.removeEventListener("visibilitychange", handleVisibilityChange);
  window.removeEventListener("resize", checkMobile);
});
</script>

<style scoped lang="scss">
@use "@/styles/user-theme.scss" as *;

// 移动端适配
@include mobile {
  .home-container {
    @include mobile-container;

    background: #f5f7fa;
  }

  .main-content {
    display: flex;
    flex-direction: column;
    gap: 0;
    padding: 0;
    margin: 0;
  }

  // 显示移动端分类导航
  .mobile-category-nav {
    position: sticky;
    top: 0;
    z-index: 10;
    display: block;
    padding: 0 16px;
    background: white;
    border-bottom: 1px solid #f0f2f5;
  }

  // 隐藏桌面端侧边栏
  .desktop-only {
    display: none;
  }

  .center-content {
    padding: 16px;

    // 移动端搜索和排序区域
    .search-sort-section {
      margin-bottom: 16px;
      background: white;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgb(0 0 0 / 6%);

      .search-wrapper {
        display: flex;
        gap: 8px;
        padding: 12px;
        border-bottom: 1px solid #f0f2f5;

        .search-input {
          flex: 1;

          :deep(.el-input__wrapper) {
            padding: 10px 14px;
            border: 1px solid #e4e7ed;
            border-radius: 8px;
            transition: all 0.3s ease;

            &:hover {
              border-color: #409eff;
            }

            &.is-focus {
              border-color: #409eff;
              box-shadow: 0 0 0 2px rgb(64 158 255 / 10%);
            }
          }

          :deep(.el-input__inner) {
            font-size: 14px;
            color: #303133;

            &::placeholder {
              color: #909399;
            }
          }

          .search-icon {
            font-size: 16px;
            color: #909399;
          }
        }

        .search-btn {
          padding: 10px 16px;
          font-size: 14px;
          font-weight: 500;
          border-radius: 8px;
          transition: all 0.3s ease;

          .el-icon {
            margin-right: 4px;
          }

          .btn-text {
            display: none;
          }

          &:active {
            transform: scale(0.95);
          }
        }
      }

      .sort-tabs {
        display: flex;
        align-items: center;
        padding: 12px;

        .sort-label {
          flex-shrink: 0;
          margin-right: 12px;
          font-size: 14px;
          font-weight: 500;
          color: #606266;
        }

        .sort-options {
          display: flex;
          flex: 1;
          gap: 8px;
          overflow-x: auto;
          scrollbar-width: none;

          &::-webkit-scrollbar {
            display: none;
          }

          .sort-item {
            display: flex;
            flex-shrink: 0;
            gap: 4px;
            align-items: center;
            padding: 6px 12px;
            font-size: 13px;
            color: #606266;
            white-space: nowrap;
            cursor: pointer;
            background: #f5f7fa;
            border: 1px solid transparent;
            border-radius: 6px;
            transition: all 0.3s ease;

            .el-icon {
              font-size: 14px;
            }

            &:hover {
              color: #409eff;
              background: #ecf5ff;
              border-color: #b3d8ff;
            }

            &.active {
              color: #fff;
              background: #409eff;
              border-color: #409eff;
              box-shadow: 0 2px 4px rgb(64 158 255 / 20%);
            }
          }
        }
      }
    }

    .article-list {
      display: flex;
      flex-direction: column;
      gap: 12px;

      .article-card {
        overflow: hidden;
        cursor: pointer;
        background: white;
        border-radius: 16px;
        box-shadow: 0 2px 12px rgb(0 0 0 / 8%);
        transition: all 0.3s ease;

        &:active {
          transform: scale(0.98);
        }

        .mobile-article-layout {
          padding: 16px;

          .article-header {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            margin-bottom: 12px;

            .author-section {
              .author-info {
                display: flex;
                gap: 8px;
                align-items: center;
                cursor: pointer !important;

                .author-avatar {
                  flex-shrink: 0;

                  :deep(.el-avatar) {
                    transition: all 0.3s ease;
                  }
                }

                .author-details {
                  display: flex;
                  flex-direction: column;
                  gap: 2px;

                  .author-name {
                    font-size: 13px;
                    font-weight: 500;
                    color: #6b7280;
                    cursor: pointer;
                    transition: color 0.3s ease;

                    &:hover {
                      color: #409eff;
                    }
                  }

                  .publish-time {
                    font-size: 11px;
                    color: #9ca3af;
                  }
                }
              }
            }

            .article-meta {
              display: flex;
              gap: 8px;
              align-items: center;

              .publish-time {
                font-size: 12px;
                color: #9ca3af;
              }

              .article-badge {
                padding: 2px 6px;
                font-size: 10px;
                border-radius: 4px;
              }
            }
          }

          .article-main {
            display: flex;
            gap: 12px;
            margin-bottom: 12px;

            .article-content {
              flex: 1;

              .article-title {
                display: -webkit-box;
                margin-bottom: 8px;
                overflow: hidden;
                -webkit-line-clamp: 2;
                line-clamp: 2;
                font-size: 16px;
                font-weight: 600;
                line-height: 1.4;
                color: #1f2937;
                -webkit-box-orient: vertical;
              }

              .article-summary {
                display: -webkit-box;
                margin-bottom: 12px;
                overflow: hidden;
                -webkit-line-clamp: 2;
                line-clamp: 2;
                font-size: 14px;
                line-height: 1.5;
                color: #6b7280;
                -webkit-box-orient: vertical;
              }

              // 标签和操作按钮容器样式
              .tags-actions-row {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding-top: 12px;
                margin-top: 12px;
                border-top: 1px solid #f3f4f6;

                .article-tags {
                  display: flex;
                  flex: 1;
                  flex-wrap: wrap;
                  gap: 6px;
                  margin: 0;

                  .tag-item {
                    padding: 3px 8px;
                    font-size: 11px;
                    font-weight: 500;
                    white-space: nowrap;
                    border-radius: 12px;
                    transition: all 0.2s ease;

                    &:hover {
                      box-shadow: 0 1px 4px rgb(0 0 0 / 15%);
                      transform: scale(1.05);
                    }
                  }
                }

                .right-actions {
                  display: flex;
                  gap: 12px;
                  align-items: center;
                  padding-left: 12px;
                  margin: 0;

                  .stat-item {
                    display: flex;
                    gap: 4px;
                    align-items: center;
                    font-size: 12px;
                    color: #9ca3af;

                    .el-icon {
                      font-size: 13px;
                    }

                    .stat-text {
                      font-weight: 500;
                    }
                  }

                  .action-btn {
                    display: flex;
                    gap: 3px;
                    align-items: center;
                    min-width: 32px;
                    min-height: 32px;
                    padding: 6px 10px;
                    font-size: 12px;
                    font-weight: 500;
                    color: #6b7280;
                    background: #f9fafb;
                    border: 1px solid #e5e7eb;
                    border-radius: 16px;
                    transition: all 0.3s ease;

                    .el-icon {
                      font-size: 14px;
                    }

                    .action-text {
                      font-size: 11px;
                      font-weight: 600;
                    }

                    &:hover {
                      color: #1e80ff;
                      background: #f0f8ff;
                      border-color: #b3d9ff;
                    }

                    &.is-liked {
                      color: #dc2626;
                      background: #fef2f2;
                      border-color: #fecaca;

                      .liked-icon {
                        animation: like-animation 0.3s ease;
                      }
                    }

                    &.is-collected {
                      color: #d97706;
                      background: #fffbeb;
                      border-color: #fed7aa;

                      .collected-icon {
                        animation: collect-animation 0.3s ease;
                      }
                    }
                  }
                }
              }

              .article-tags {
                display: flex;
                flex-wrap: wrap;
                gap: 6px;

                .tag-item {
                  padding: 3px 8px;
                  font-size: 11px;
                  font-weight: 500;
                  border-radius: 12px;
                }
              }
            }

            .article-cover {
              flex-shrink: 0;
              width: 80px;
              height: 80px;
              overflow: hidden;
              border-radius: 12px;

              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
          }

          .article-footer {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-top: 12px;
            border-top: 1px solid #f3f4f6;

            .article-stats {
              display: flex;
              gap: 16px;

              .stat-item {
                display: flex;
                gap: 4px;
                align-items: center;
                font-size: 13px;
                color: #9ca3af;

                .el-icon {
                  font-size: 14px;
                }

                .stat-text {
                  font-weight: 500;
                }
              }
            }

            .article-actions {
              display: flex;
              gap: 8px;

              .action-btn {
                display: flex;
                gap: 4px;
                align-items: center;
                min-width: 36px;
                min-height: 36px;
                padding: 6px 12px;
                font-size: 13px;
                font-weight: 500;
                color: #6b7280;
                background: #f9fafb;
                border: 1px solid #e5e7eb;
                border-radius: 18px;
                transition: all 0.3s ease;

                .el-icon {
                  font-size: 16px;
                }

                .action-text {
                  font-weight: 600;
                }

                &.is-liked {
                  color: #dc2626;
                  background: #fef2f2;
                  border-color: #fecaca;

                  .liked-icon {
                    animation: like-animation 0.3s ease;
                  }
                }

                &.is-collected {
                  color: #d97706;
                  background: #fffbeb;
                  border-color: #fed7aa;

                  .collected-icon {
                    animation: collect-animation 0.3s ease;
                  }
                }
              }
            }
          }
        }
      }

      .pagination-wrapper {
        display: flex;
        justify-content: center;
        padding: 20px 0;
        margin-top: 16px;

        :deep(.el-pagination) {
          .el-pager li {
            min-width: 36px;
            height: 36px;
            margin: 0 2px;
            line-height: 34px;
            border-radius: 8px;
          }

          .btn-prev,
          .btn-next {
            min-width: 36px;
            height: 36px;
            border-radius: 8px;
          }
        }
      }
    }
  }
}

// 小屏幕移动端优化
@include mobile-xs {
  .home-container {
    padding: 0 12px;
  }

  .mobile-category-nav {
    padding: 0 12px;

    .category-scroll .category-item {
      padding: 8px 12px;
      font-size: 13px;

      .category-count {
        font-size: 11px;
      }
    }
  }

  .center-content {
    padding: 12px;

    .article-list .article-card .mobile-article-layout {
      padding: 12px;

      .article-main .article-content {
        .article-title {
          font-size: 15px;
        }

        .article-summary {
          font-size: 13px;
        }

        .tags-actions-row {
          flex-direction: column;
          gap: 8px;
          align-items: flex-start;

          .article-tags {
            position: relative;
            width: 100%;
            max-height: 60px;
            overflow: hidden;

            &::after {
              position: absolute;
              top: 0;
              right: 0;
              width: 20px;
              height: 100%;
              pointer-events: none;
              content: "";
              background: linear-gradient(to left, white, transparent);
            }
          }

          .right-actions {
            padding-left: 0;

            .action-btn {
              min-width: 30px;
              min-height: 30px;
              padding: 4px 8px;
              font-size: 11px;
              border-radius: 15px;

              .action-text {
                font-size: 10px;
              }
            }
          }
        }
      }
    }
  }
}

// iPhone XR 专用优化
@include iphone-xr {
  .home-container {
    padding-right: max(16px, env(safe-area-inset-right));
    padding-bottom: env(safe-area-inset-bottom);

    /* 考虑安全区域 */
    padding-left: max(16px, env(safe-area-inset-left));
  }

  .center-content .article-list .article-card .mobile-article-layout {
    .tags-actions-row .right-actions .action-btn {
      min-width: 44px;
      min-height: 44px; // iOS推荐的最小触摸目标
      padding: 8px 12px;
      font-size: 12px;

      .action-text {
        font-size: 11px;
      }
    }
  }
}

// 平板适配
@include tablet {
  .main-content {
    display: grid;
    grid-template-columns: 200px 1fr 280px;
    gap: 20px;
    padding: 20px;

    .mobile-category-nav {
      display: none;
    }

    .desktop-only {
      display: block;
    }

    .left-sidebar {
      .sidebar-menu {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .menu-item {
          padding: 8px 12px;
          border-radius: 6px;
        }
      }
    }

    .center-content {
      padding: 0;
    }
  }
}

// 桌面端适配
@include desktop {
  .main-content {
    grid-template-columns: 240px 1fr 320px;
    gap: 24px;
    padding: 24px;
  }
}

// 桌面端中间内容区
@include desktop {
  .center-content {
    flex: 1;

    // 搜索和排序区域
    .search-sort-section {
      margin-bottom: 20px;
      background: white;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
      }

      .search-wrapper {
        display: flex;
        gap: 12px;
        padding: 16px;
        border-bottom: 1px solid #f0f2f5;

        .search-input {
          flex: 1;

          :deep(.el-input__wrapper) {
            border: 1px solid #e4e7ed;
            border-radius: 8px;
            transition: all 0.3s ease;

            &:hover {
              border-color: #409eff;
            }

            &.is-focus {
              border-color: #409eff;
              box-shadow: 0 0 0 2px rgb(64 158 255 / 10%);
            }
          }

          :deep(.el-input__inner) {
            font-size: 15px;
            color: #303133;

            &::placeholder {
              color: #909399;
            }
          }

          .search-icon {
            font-size: 16px;
            color: #909399;
          }
        }

        .search-btn {
          padding: 12px 24px;
          font-size: 15px;
          font-weight: 500;
          border-radius: 8px;
          transition: all 0.3s ease;

          .el-icon {
            margin-right: 6px;
            font-size: 16px;
          }

          &:hover {
            box-shadow: 0 4px 12px rgb(64 158 255 / 30%);
            transform: translateY(-2px);
          }

          &:active {
            transform: translateY(0);
          }
        }
      }

      .sort-tabs {
        display: flex;
        align-items: center;
        padding: 12px 16px;

        .sort-label {
          flex-shrink: 0;
          margin-right: 16px;
          font-size: 14px;
          font-weight: 500;
          color: #606266;
        }

        .sort-options {
          display: flex;
          gap: 8px;
          align-items: center;

          .sort-item {
            display: flex;
            gap: 6px;
            align-items: center;
            padding: 8px 16px;
            font-size: 14px;
            color: #606266;
            cursor: pointer;
            background: #f5f7fa;
            border: 1px solid transparent;
            border-radius: 6px;
            transition: all 0.3s ease;

            .el-icon {
              font-size: 14px;
            }

            &:hover {
              color: #409eff;
              background: #ecf5ff;
              border-color: #b3d8ff;
              transform: translateY(-2px);
            }

            &.active {
              font-weight: 500;
              color: #fff;
              background: #409eff;
              border-color: #409eff;
              box-shadow: 0 2px 8px rgb(64 158 255 / 30%);
            }

            &:active {
              transform: translateY(0);
            }
          }
        }
      }
    }

    .article-list {
      .article-card {
        display: flex;
        gap: 16px;
        padding: 20px;
        margin-bottom: 16px;
        cursor: pointer;
        background: white;
        border-radius: 8px;
        box-shadow: 0 1px 2px rgb(0 0 0 / 4%);
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
          transform: translateY(-2px);
        }

        .mobile-article-layout {
          display: flex;
          flex-direction: column;
          width: 100%;
          padding: 0;

          .article-header {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            margin-bottom: 16px;

            .author-section {
              flex: 1;

              .author-info {
                display: flex;
                gap: 10px;
                align-items: flex-start;

                .author-avatar {
                  flex-shrink: 0;
                  width: 28px;
                  height: 28px;
                  overflow: hidden;
                  border-radius: 50%;
                }

                .author-details {
                  display: flex;
                  flex-direction: column;
                  gap: 2px;

                  .author-name {
                    font-size: 14px;
                    font-weight: 400;
                    line-height: 1.2;
                    color: #4a5568;
                    letter-spacing: 0.01em;
                    cursor: pointer;
                    transition: color 0.3s ease;

                    &:hover {
                      color: #409eff;
                    }
                  }

                  .publish-time {
                    font-size: 12px;
                    font-weight: 400;
                    line-height: 1.2;
                    color: #a0aec0;
                  }
                }
              }
            }

            .article-meta {
              display: flex;
              gap: 8px;
              align-items: center;
              margin-left: 12px;

              .article-badge {
                padding: 2px 6px;
                font-size: 11px;
                font-weight: 500;
                border: none;
                border-radius: 4px;

                &.el-tag--danger {
                  color: #c53030;
                  background-color: #fed7d7;
                }

                &.el-tag--success {
                  color: #2f855a;
                  background-color: #c6f6d5;
                }
              }
            }
          }

          .article-main {
            display: flex;
            flex: 1;
            gap: 16px;
            margin-bottom: 0;

            .article-content {
              display: flex;
              flex: 1;
              flex-direction: column;

              .article-title {
                margin: 0 0 8px;
                font-size: 18px;
                font-weight: 600;
                line-height: 1.4;
                color: #1d2129;
              }

              .article-summary {
                display: -webkit-box;
                flex: 1;
                margin: 0 0 16px;
                overflow: hidden;
                -webkit-line-clamp: 2;
                line-clamp: 2;
                font-size: 14px;
                line-height: 1.6;
                color: #515767;
                -webkit-box-orient: vertical;
              }

              // 标签和操作栏的容器
              .tags-actions-row {
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-top: auto;

                .article-tags {
                  display: flex;
                  flex: 1;
                  flex-wrap: wrap;
                  gap: 8px;
                  margin: 0;

                  .tag-item {
                    padding: 4px 10px;
                    font-size: 12px;
                    font-weight: 500;
                    white-space: nowrap;
                    border-radius: 12px;
                    transition: all 0.2s ease;

                    &:hover {
                      box-shadow: 0 2px 6px rgb(0 0 0 / 15%);
                      transform: translateY(-1px);
                    }
                  }
                }

                .right-actions {
                  display: flex;
                  gap: 12px;
                  align-items: center;
                  padding: 0;
                  margin: 0;

                  > * {
                    padding: 0;
                    margin: 0;
                  }

                  .stat-item {
                    display: flex;
                    gap: 4px;
                    align-items: center;
                    padding: 0;
                    margin: 0;
                    font-size: 13px;
                    color: #8a919f;

                    .el-icon {
                      font-size: 14px;
                    }
                  }

                  .action-btn {
                    display: flex;
                    gap: 4px;
                    align-items: center;
                    padding: 4px 8px;
                    margin: 0;
                    font-size: 14px;
                    color: #8a919f;
                    background: transparent;
                    border: none;
                    border-radius: 4px;
                    transition: all 0.3s ease;

                    &:hover {
                      color: #1e80ff;
                      background: rgb(30 128 255 / 6%);
                    }

                    &.is-liked {
                      color: #ff4757;

                      &:hover {
                        color: #ff3742;
                        background: rgb(255 71 87 / 6%);
                      }
                    }

                    &.is-collected {
                      color: #ffa502;

                      &:hover {
                        color: #ff9500;
                        background: rgb(255 165 2 / 6%);
                      }
                    }
                  }
                }
              }
            }

            .article-cover {
              flex-shrink: 0;
              width: 120px;
              height: 80px;
              overflow: hidden;
              border-radius: 8px;

              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
          }
        }
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      padding: 16px 0;
      margin-top: 32px;
    }
  }
}

// 动画效果
@keyframes like-animation {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.2);
  }

  100% {
    transform: scale(1);
  }
}

@keyframes collect-animation {
  0% {
    transform: scale(1) rotate(0deg);
  }

  50% {
    transform: scale(1.1) rotate(10deg);
  }

  100% {
    transform: scale(1) rotate(0deg);
  }
}

// 移动端触摸反馈
@include mobile {
  .article-card {
    &:active {
      transform: scale(0.98);
      transition: transform 0.1s ease;
    }
  }

  .category-item {
    &:active {
      transform: scale(0.95);
      transition: transform 0.1s ease;
    }
  }

  .action-btn {
    &:active {
      transform: scale(0.9);
      transition: transform 0.1s ease;
    }
  }
}

// 淮入动画
@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 基础样式
.home-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

// 主要内容区域
.main-content {
  display: flex;
  gap: $spacing-lg;
  max-width: 1400px;
  padding: $spacing-lg;
  margin: 0 auto;
}

// 移动端分类导航
.mobile-category-nav {
  display: none;

  .category-scroll {
    display: flex;
    gap: 8px;
    padding: 12px 0;
    overflow-x: auto;
    scrollbar-width: none;
    -ms-overflow-style: none;

    &::-webkit-scrollbar {
      display: none;
    }

    .category-item {
      display: flex;
      flex-shrink: 0;
      gap: 6px;
      align-items: center;
      padding: 10px 16px;
      font-size: 14px;
      color: #4e5969;
      white-space: nowrap;
      cursor: pointer;
      background: white;
      border: 1px solid #e4e6ea;
      border-radius: 24px;
      transition: all 0.3s ease;

      &.active {
        color: white;
        background: #1e80ff;
        border-color: #1e80ff;
        box-shadow: 0 2px 8px rgb(30 128 255 / 30%);
      }

      .category-icon {
        font-size: 16px;
      }

      .category-name {
        font-weight: 500;
      }

      .category-count {
        font-size: 12px;
        opacity: 0.8;
      }
    }
  }
}

// 桌面端显示/隐藏控制
.desktop-only {
  display: block;
}

// 桌面端左侧导航
.left-sidebar {
  flex-shrink: 0;
  width: 220px;

  .sidebar-menu {
    position: sticky;
    top: 80px; // 考虑顶部导航栏的高度
    padding: $spacing-sm 0;
    background: white;
    border: 1px solid rgb(0 0 0 / 5%);
    border-radius: $border-radius-large;
    box-shadow: $shadow-card;

    .menu-item {
      position: relative;
      display: flex;
      align-items: center;
      padding: 12px $spacing-md;
      margin: 2px $spacing-sm;
      color: $text-dark-primary;
      cursor: pointer;
      border-radius: $border-radius-medium;
      transition: $transition-smooth;

      &:hover {
        color: #409eff;
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        transform: translateX(2px);
      }

      &.active {
        color: white;
        background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
        box-shadow: $shadow-light;

        .el-icon {
          color: white;
        }
      }

      .el-icon {
        font-size: 16px;
        color: #8a919f;
        transition: $transition-smooth;
      }

      span {
        margin-left: $spacing-sm;
        font-size: 14px;
        font-weight: 500;
      }

      .article-count {
        margin-left: auto;
        font-size: 12px;
        color: #8a919f;
      }
    }
  }
}

// 桌面端右侧边栏
.right-sidebar {
  flex-shrink: 0;
  width: 280px;

  .sidebar-sticky {
    position: sticky;
    top: 80px;
    max-height: calc(100vh - 100px);
    overflow-y: auto;
    scrollbar-color: rgb(221 222 224) transparent;

    // 自定义滚动条样式
    scrollbar-width: thin;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }

    &::-webkit-scrollbar-thumb {
      background-color: rgb(221 222 224);
      border-radius: 4px;

      &:hover {
        background: rgb(199 201 203);
      }
    }
  }

  .greeting-card {
    padding: 20px;
    margin-bottom: 16px;
    color: white;
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    border-radius: 8px;

    .greeting-content {
      h3 {
        margin: 0 0 8px;
        font-size: 18px;
      }

      p {
        margin: 0;
        font-size: 14px;
        opacity: 0.9;
      }
    }
  }

  // 榜单容器 - 自然流式布局
  .rankings-container {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .ranking-card,
  .author-rank {
    padding: 20px;
    margin-bottom: 16px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgb(0 0 0 / 4%);

    .ranking-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;

      h4 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #1d2129;
      }

      .ranking-actions {
        display: flex;
        gap: 12px;

        .refresh-btn,
        .more-btn {
          font-size: 12px;
          color: #86909c;
          cursor: pointer;
          transition: color 0.2s;

          &:hover {
            color: #1677ff;
          }
        }
      }
    }

    h4 {
      margin: 0 0 16px;
      font-size: 16px;
      font-weight: 600;
      color: #1d2129;
    }

    .rank-list {
      .rank-item {
        display: flex;
        align-items: center;
        padding: 10px 0;
        cursor: pointer;
        border-bottom: 1px solid #f2f3f5;
        transition: all 0.2s ease;

        &:last-child {
          border-bottom: none;
        }

        &:hover {
          padding-right: 8px;
          padding-left: 8px;
          background-color: #f8fafc;
          border-radius: 6px;
        }

        .rank-number {
          flex-shrink: 0;
          width: 20px;
          margin-right: 10px;
          font-size: 14px;
          font-weight: 700;
          color: #8a919f;
          text-align: center;
        }

        // 前三名的特殊颜色
        &:nth-child(1) .rank-number {
          font-size: 16px;
          color: #ff4d4f; // 红色
        }

        &:nth-child(2) .rank-number {
          font-size: 16px;
          color: #ff7a45; // 橙色
        }

        &:nth-child(3) .rank-number {
          font-size: 16px;
          color: #ffc53d; // 黄色
        }

        .article-info {
          flex: 1;
          min-width: 0; // 允许flex子项收缩

          .article-title {
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 14px;
            line-height: 1.5;
            color: #1d2129;
            white-space: nowrap;
            cursor: pointer;
            transition: color 0.2s ease;

            &:hover {
              color: #409eff;
            }
          }
        }

        .author-avatar {
          flex-shrink: 0;
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover {
            box-shadow: 0 2px 8px rgb(64 158 255 / 30%);
            transform: scale(1.05);
          }
        }

        .author-info {
          flex: 1;
          margin-left: 12px;
          cursor: pointer;

          .author-name {
            margin-bottom: 6px;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 14px;
            font-weight: 600;
            color: #1d2129;
            white-space: nowrap;
            transition: color 0.3s ease;

            &:hover {
              color: #409eff;
            }
          }

          .author-desc {
            display: flex;
            gap: 12px;
            font-size: 12px;
            color: #8a919f;

            .stat-item {
              display: flex;
              gap: 4px;
              align-items: center;

              .el-icon {
                font-size: 12px;
              }
            }
          }
        }

        .follow-btn {
          flex-shrink: 0;
          min-width: 68px;
          height: 32px;
          padding: 0 16px;
          font-size: 13px;
          font-weight: 500;
          border-radius: 16px;
          transition: all 0.3s ease;

          &:hover {
            box-shadow: 0 2px 8px rgb(64 158 255 / 20%);
            transform: translateY(-1px);
          }

          &:active {
            transform: translateY(0);
          }

          &.el-button--info {
            &:hover {
              background-color: #f5f7fa;
              border-color: #d3d4d6;
            }
          }
        }
      }
    }

    // 作者榜专属样式
    .author-list {
      .author-item {
        display: flex;
        align-items: center;
        padding: 12px 0;
        transition: all 0.2s ease;

        &:last-child {
          border-bottom: none;
        }

        .author-avatar {
          flex-shrink: 0;
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover {
            opacity: 0.8;
          }
        }

        .author-info {
          flex: 1;
          min-width: 0;
          margin-left: 12px;
          cursor: pointer;

          .author-name {
            margin-bottom: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 14px;
            font-weight: 500;
            line-height: 1.5;
            color: #252933;
            white-space: nowrap;
          }

          .author-signature {
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 13px;
            line-height: 1.5;
            color: #8a919f;
            white-space: nowrap;
          }
        }

        .follow-text {
          flex-shrink: 0;
          font-size: 14px;
          color: #1e80ff;
          cursor: pointer;
          user-select: none;
          transition: all 0.2s ease;

          &:hover {
            color: #409eff;
          }

          &.is-followed {
            color: #8a919f;
          }
        }
      }
    }
  }
}
</style>
